package com.zhichat.web.socket.netty.handler;

import com.zhichat.infrastructure.util.ThreadLocalCache;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName: HearBeatHandler
 * @Description: netty心跳超时事件触发handler
 * @Author: 团长九哥 https://space.bilibili.com/602197686
 * @CreateDate: 2024/11/29 17:45
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class WsHearBeatHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE:
                    log.info("{} - 读空闲事件触发", ThreadLocalCache.getUserId());
                    ctx.close();
                    break;
                case WRITER_IDLE:
                    log.info("{} - 写空闲事件触发", ThreadLocalCache.getUserId());
                    ctx.writeAndFlush("ping");
                    break;
                case ALL_IDLE:
                    log.info("{} - 读写空闲事件触发", ThreadLocalCache.getUserId());
                    break;
                default:
                    break;
            }
        }
    }
}
